<!-- 整车故障率统计-->

<template>
    <div class="wrapper">
        <!-- 报表标题组件-->
        <ReportTitle :titleInfo="titleInfo" @handleExport="handleExport" />
        <!-- 报表检索条件组件 -->
        <ReportSearch :loading="loading" :searchFormDatas="searchFormDatas" v-model:searchForm="searchForm"
            @handleSearchForm="handleSearchForm" @handleResetForm="handleResetForm" />
        <!-- 报表表格标题组件-->
        <ReportTableTitle :tableTitle="tableTitle" />
        <!-- 报表表格组件-->
        <ReportTable :loading="loading" :tableData="tableData" :pageInfo="pageInfo" :tableColumnData="tableColumnData" :tableColumnWidthData="tableColumnWidthData" />
        <!-- 报表表格分页组件-->
        <ReportTablePage v-model:pageInfo="pageInfo" @handleSearchForm="handleSearchForm" />
    </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

import ReportTitle from '@/components/reportTitle/index.vue';
import ReportSearch from '@/components/reportSearch/index.vue';
import ReportTableTitle from '@/components/reportTableTitle/index.vue';
import ReportTable from '@/components/reportTable/index.vue';
import ReportTablePage from '@/components/reportTablePage/index.vue';

import * as local from '@/utils/cache/localStorage';
import * as server from '@/api/modules/maintainStatis';
import * as cookies from "@/utils/cache/cookies";

import { MaintenanceStatisDimensionOptions } from '@/constant/selectOptions';
import { getYesterday } from '@/utils/date';
import { apiFn, deepCopy, exportReportFile } from '@/utils/utilFns';

// 报表标题信息
const titleInfo = reactive({
    title: '整车故障率统计',
    description: ""
});

// 报表表格标题
const defaultTitle = '整车故障率统计';
const tableTitle = ref(defaultTitle);

// 默认表单数据
const defaultSearchForm = {
    mapId: local.getItem('defaultMapId'),
    dateType: '1',
    timeFrame: [getYesterday(0), getYesterday(0)],
	vehicleType: '',
	statisticType: '0',
};

// 默认分页数据
const defaultPageInfo = {
    currentPage: 1,
    pageSize: 20,
    total: 0
};

// 加载状态
const loading = ref(false);
const orgId = ref(local.getItem('defaultIdPath'));

// 表头数据
const tableColumnData = ref([]);

// 表格数据
const tableData = ref([]);

// 表头宽度数据
const tableColumnWidthData = {};

// 检索条件数据
const searchFormDatas = ref([
    {
        id: 0,
        type: 'select',
        label: '所属组织',
        prop: 'mapId',
        options: local.getItem('mineList'),
        api: () => { },
        placeholder: '请选择所属组织',
        rules: [{ required: true, message: '请选择所属组织', trigger: ['blur, change'] }]
    },
    {
        id: 1,
        type: 'dateRangePicker',
        prop: 'timeFrame',
        label: '时间范围',
        options: [],
        api: () => { },
        placeholder: '请选择时间范围',
        rules: [{ required: true, message: '请选择时间范围', trigger: ['change'] }]
    },
    {
        id: 2,
        type: 'select',
        label: '统计维度',
        prop: 'statisticType',
        options: MaintenanceStatisDimensionOptions,
        clearable: false,
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 3,
        type: 'select',
        label: '车型',
        prop: 'vehicleType',
        options: [],
        clearable: false,
        api: () => { },
        placeholder: '请选择',
    },
]);

// 表单数据
const searchForm = reactive(deepCopy(defaultSearchForm));

// 分页数据
const pageInfo = reactive(deepCopy(defaultPageInfo));

onMounted(() => {
    getVehicleTypeOptions();
});

// 所属组织变化监听
watch(() => searchForm.mapId, (val) => {
    searchForm.vehicleNo = '';

    getOrgId(val);
});

const getOrgId = (val) => {
    const mineList = local.getItem('mineList');

    const target = mineList.find(item => item.mapId === val);

    target && (orgId.value = target.id);
};

// 获取车型
const getVehicleTypeOptions = () => {
    let params = {
        orgId: orgId.value,
    };

    apiFn(server.getVehicleTypeList, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                const options = data.map(item => {
                    return { name: item, value: item};
                });
                searchFormDatas.value[3]['options'] = options
            }
        }).catch(() => {
            searchFormDatas.value[3]['options'] = [];
        });
};

// 获取查询参数
const getParams = () => {
    const { vehicleNo, timeFrame } = searchForm;
    const { pageSize, currentPage } = pageInfo;

    const params = {
        orgId: orgId.value,
		startTime: timeFrame[0],
		endTime: timeFrame[1],
		vehicleNo,
        limit: pageSize,
        page: currentPage,
    };

    return params;
};

// 获取报表表头
const getTableColumn = () => {
    const params = getParams();
    apiFn(server.getFinishedCarTableColumn, params)
        .then(res => {
            const { code, data = [], resultMsg = '' } = res;
            if (code === '200') {
                tableColumnData.value = data;
                tableTitle.value = resultMsg;
                getTableList();
            } else {
                tableColumnData.value = [];
                tableTitle.value = defaultTitle;
            }
        }).catch(() => {
            tableColumnData.value = [];
            tableTitle.value = defaultTitle;
        })
};

// 获取报表列表内容
const getTableList = () => {
    const params = getParams();
    loading.value = true;
    apiFn(server.getFinishedCarTableList, params)
        .then(res => {
            const { code, data, recordsTotal } = res;
            if (code === '200') {
                if (data.length > 0) {
                    tableData.value = data;
                } else {
                    tableData.value = [];
                }

                pageInfo.total = recordsTotal;
            }
        }).catch(() => {
            tableData.value = [];
            pageInfo.total = 0;
        }).finally(() => {
            loading.value = false;
        })
};

// 查询
const handleSearchForm = (type) => {
    if (loading.value) return;

    if (type === 'search') {
        Object.keys(defaultPageInfo).forEach(key => {
            if (key in pageInfo) {
                pageInfo[key] = defaultPageInfo[key];
            }
        })
    }
    getTableColumn();
};

// 导出
const handleExport = () => {
    if (!tableData.value.length) {
        ElMessage.warning('无查询数据导出!');
        return;
    }

    const url = window.config.APP_BASE_URL + "fault/exportFaultVehicleTypeList";
    const params = getParams();

    exportReportFile(url, "POST", {
        ElMessage: ElMessage,
        token: cookies.getToken(),
        params: params,
    });
};

// 重置
const handleResetForm = () => {
    Object.keys(searchForm).forEach(key => {
        if (key in defaultSearchForm) {
            searchForm[key] = defaultSearchForm[key];
        }
    });

    Object.keys(defaultPageInfo).forEach(key => {
        if (key in pageInfo) {
            pageInfo[key] = defaultPageInfo[key];
        }
    });

    tableTitle.value = defaultTitle;
    tableColumnData.value = [];
    tableData.value = [];
};
</script>

<style lang="scss" scoped></style>